from epics import PV
import time
from os import environ
from os.path import isfile
environ["EPICS_CA_ADDR_LIST"]="127.0.0.1 10.10.14.200 10.10.14.201"

class _PV():
    def __init__(self):
        self.normal_F = False
        self.interlock_F = False
        self.BPM_limit_set = PV("BPM1:SetX1_Limit1")
        self.BPM_Reset_Set = PV("BPM:ResetFastInterlock")

        self.WR_Reset_set = PV("TIMS:WR:Reset_Bos")
        self.WR_Interlock_status = PV("TIMS:WR:Enable_Bos")
        self.Wait_status = PV("TIMS:WR:Wait_State")

        self.Ready_status10 = PV("TIMS:WR:TS_node10:HeartBeat_Ready")
        self.Ready_status11 = PV("TIMS:WR:TS_node11:HeartBeat_Ready")

        self.BPM_interlock_status = PV("TIMS:WR:TS_node11:InterLock",callback= self.onValueChange)
        

    def interlock(self):
        print("修改BPM阈值为0")
        self.BPM_limit_set.put(0)

    def normal(self):
        print("修改BPM阈值为100000")
        self.BPM_limit_set.put(100000)
        print("复位")
        self.BPM_Reset_Set.put(1)
        self.BPM_Reset_Set.put(1)
        self.BPM_Reset_Set.put(1)
        self.BPM_Reset_Set.put(0)

    def onValueChange(self,pvname=None, value=None, host=None, **kws):
        if value == 1:
            self.normal_F = True
        if value == 0:
            self.interlock_F = True
        # print(f'PV value changed: {pvname} ({host})  {value}')  


if __name__ == "__main__":
    i = 0
    j = 0
    k = 0
    pv = _PV()
    if not isfile("BPS_test.csv"):
        fp = open("BPS_test.csv","w")
        fp.write("测试时间,测试次数,连锁次数,恢复次数\n")
    else:
        fp = open("BPS_test.csv","a+")
    while True:
        i += 1
        print(f"=====================================\n第{i}次测试开始")
        pv.interlock()
        while True:
            if pv.interlock_F:
                break
        time.sleep(200)
        if pv.WR_Interlock_status.get() == 0 and pv.BPM_interlock_status.get() == 0:
            j += 1

        pv.normal()
        while True:
            if pv.normal_F:
                break
        time.sleep(50)
        if pv.WR_Interlock_status.get() == 1 and pv.BPM_interlock_status.get() == 1:
            k += 1
        fp.write("{},{},{},{}\n".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),i,j,k))
        fp.flush()
        
        
    fp.close()

